import './index.scss'
import { useRef, useState, useEffect, useCallback } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { songflag, playSong, songingFlag } from '../../store/actions'
import { Slider } from 'antd-mobile';
import Musicing from '../musicing'
import Circle from '../circle'
function Music (props) {
    const Audio = useRef(null)
    const dispatch = useDispatch()
    const [audioTime,setAudioTime] =  useState(0)
    const songList = useSelector(state => state.reducer.song)
    const songType = useSelector(state => state.reducer.songType) // loop 单曲循环绑定
    const playFlag = useSelector(state => state.reducer.songFlag)
    const a = (e) => {
        e.stopPropagation()
        dispatch(songflag(!playFlag))
    }
    useEffect(() => {
        if(playFlag) {
            Audio.current.play()
            Slideraudio()
        } else {
            Audio.current.pause()
            Audio.current.removeEventListener('timeupdate',setTime)
        }
    }, [playFlag])
    // 初始化监听播放和停止
    useEffect(() => {
        Audio.current.addEventListener("play", function(){
            if(!playFlag){
                dispatch(songflag(true))
            }
        })
        Audio.current.addEventListener("pause", function(){
            if(playFlag){
                console.log(123)
                dispatch(songflag(false))
            }
        })
    },[])
    const [ended, setEnded] = useState(false)
    const nextSonga = () => {
        setEnded(Audio.current.ended)
    }
    // 下一首 上一首
    const nextSong = (type, auto) => {
        // type : +1:下一首;-1:上一首; auto: true正常播放完毕非手动切歌
        const index = songList.indexOf(playSongItem) // 查找播放列表index
        const length = songList.length - 1 // 播放列表最后一项
        const playSongIndex = index + type  // 点击下一首或者上一首的index
        // console.log(songType, auto, index, length)
        if(songType === 3 && auto && index === length) { // 顺序播放 最后一首时处理
            dispatch(songflag(false))
            return false
        }
        if(songType === 4) { // 随机播放处理
            dispatch(playSong(songList[parseInt(Math.random() * songList.length)]))
            return false
        }

        if(playSongIndex>length || playSongIndex<0) {
            playSongIndex > length ? dispatch(playSong(songList[0])) :  dispatch(playSong(songList[length])) // 第一首后退和最后一首前进处理
        } else {
          dispatch(playSong(songList[playSongIndex])) // 手动切歌
        }
    }
    // 播放完毕播放下一首
    useEffect(() => {
        if(ended) {
          setTimeout(() => {
            nextSong(1, true)
            setEnded(false)
          }, 2000)
        }
    },[ended])
    const Slideraudio = (i) => {
        if(i> -1) {
            i = i ? i : 0
            Audio.current.currentTime = Audio.current.duration * i / 100
            setAudioTime(i)
        }
        Audio.current.addEventListener('timeupdate',setTime, false)
    }
    const changeSlider = (i) => {
        Audio.current.removeEventListener('timeupdate',setTime)
        setAudioTime(i)
    }
    const [currentTime, setCurrentTime] = useState('00:00:00')
    const [duration, setDuration] = useState('00:00:00')
    const setTime = useCallback(() => {
        if(Audio.current.duration) {
            setCurrentTime(timeToMinute(Audio.current.currentTime))
            setDuration(timeToMinute(Audio.current.duration))
        }
        const a = (Audio.current.currentTime/Audio.current.duration) * 100
        setAudioTime(a ? parseInt(a) : 0)
      }, [])
      // 歌曲时间工具处理
    const timeToMinute = (times)=>{
        var t;
         if(times > -1){
             var hour = Math.floor(times/3600);
             var min = Math.floor(times/60) % 60;
             var sec = times % 60;
             if(hour < 10) {
                 t = '0'+ hour + ":";
             } else {
                 t = hour + ":";
             }
  
             if(min < 10){t += "0";}
             t += min + ":";
             if(sec < 10){t += "0"}
             t += sec.toFixed(2)
         }
         t=t.slice(3,-3)
         return t
        }
    const comSlider = useRef(null)
    const playSongItem = useSelector(state => state.reducer.playSong)
    useEffect(() => {
        if(playSongItem) {
          console.log(10086, playSongItem.lrc)
          Audio.current.play()
          Slideraudio()
        }
    },[playSongItem])
    const opensongingFlag = () => {
        dispatch(songingFlag(true))
    }
    const [playlistOpen, setPlaylistOpen] = useState(false)
    const changeplaylistOpen = () => {
        setPlaylistOpen(!playlistOpen)
    }
    return(
    <div className={`components-music ${playSongItem ? 'components-music-height': ''}`} >
        <Musicing value={audioTime}  currentTime={currentTime} duration={duration} onChange={changeSlider} onAfterChange={Slideraudio} nextSong={nextSong} changeplaylistOpen={changeplaylistOpen}></Musicing>
        <Slider
            ref={comSlider}
            style={{ marginLeft: 30, marginRight: 30 }}
            handleStyle={{ borderColor: '#e5473c', bordeRadius: '50%'}}
            trackStyle={{backgroundColor:'#e5473c', height:'2px'}}
            railStyle={{height:'2px'}}
            value={audioTime}
            defaultValue={0}
            min={0}
            max={100}
            onAfterChange={(i) => {Slideraudio(i)}}
            onChange={(i) => {changeSlider(i)}}
          />
        <div className="audio-play-box ali-c jus-b" onClick={opensongingFlag}>
            <div className= "audio-play-box-left-box ali-c">
              <div className={`audio-play-box-left ali-c jus-c  ratote ${playFlag ? '' : 'stop-animation'}`}>
                <div className="audio-play-box-left-bg" style={{backgroundImage: `url(${ playSongItem ? playSongItem.al.picUrl : ''})`}}></div>
              </div>
              {playSongItem && (<div className="audio-play-box-left-box-songtitle oneline">{`${playSongItem.ar[0].name} - ${playSongItem.al.name}`}</div>)}
            </div>
            <Circle value={audioTime} r="15">
                <div className={`audio-play iconfont ${playFlag ? 'icon-tingzhi1' : 'icon-caret-right1'}`}  onClick={a}>
                    <span className={`audio-play-icon iconfont ${playFlag ? 'icon-tingzhi' : 'icon-caret-right'}`}></span>
                </div>
            </Circle>
        </div>
        {/* loop */}
        {/* <audio ref={Audio} :controls="true" src="http://tyst.migu.cn/public/ringmaker01/n17/2017/07/无损/2009年06月26日博尔普斯/flac/听妈妈的话-周杰伦.flac"></audio> */}
        <audio ref={Audio} loop={songType === 2} onEnded={nextSonga}  src={`https://music.163.com/song/media/outer/url?id=${ playSongItem && playSongItem.id}.mp3`}></audio>
        <ul onClick={changeplaylistOpen} className={`component-songList ${playlistOpen ? 'component-songList-open': ''}`}>
            {songList.map((item, index) => {
                return <li key={index}>{item.name}</li>
            })}
        </ul>
        </div>)
}
export default Music

// export const zz=[
//     {
//         id:1,
//         name:'说好不哭',
//         song:"http://tyst.migu.cn/public/product8th/product38/2019/12/2617/2019年09月16日22点44分紧急内容准入纵横世代1首/歌曲下载/flac/6005479Z068.flac"
//     },
//     {
//         id:2,
//         name:'晴天',
//         song:"http://tyst.migu.cn/public/ringmaker01/n17/2017/07/无损/2009年06月26日博尔普斯/flac/晴天-周杰伦.flac"
//     },
//     {
//         id:3,
//         name:'一路向北',
//         song:"http://tyst.migu.cn/public/ringmaker01/n17/2017/07/无损/2009年06月26日博尔普斯/flac/一路向北-周杰伦.flac"
//     },
//     {
//         id:4,
//         name:'听妈妈的话',
//         song:"http://tyst.migu.cn/public/ringmaker01/n17/2017/07/无损/2009年06月26日博尔普斯/flac/听妈妈的话-周杰伦.flac"
//     },
// ]